package com.hmdp.controller;


import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.service.IUserInfoService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
@Slf4j
@RestController
@RequestMapping("/user")
@Api(description = "黑马点评用户模块")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;


    /*点击发送手机验证码执行这个方法*/
    @PostMapping("code")
    @ApiOperation(value = "点击发送手机验证码执行这个方法")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        Result result=userInfoService.sendCode(phone,session);
        return result;
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录功能")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        Result result=userInfoService.login(loginForm,session);
        return result;
    }

    /**
     * 登出功能
     * @return 无
     */
    @ApiOperation(value = "登出功能")
    @PostMapping("/logout")
    public Result logout(){
        // TODO 实现登出功能
        UserHolder.removeUser();
        return Result.ok();
    }


    @ApiOperation(value = "根据用户id查询用户的详细信息")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }


    @ApiOperation(value = "根据用户id查询用户")
    @GetMapping("/{id}")
    public Result queryUserById(@PathVariable("id") Long userId){
        /*查询详情*/
        User user = userService.getById(userId);
        if(user==null){
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        /*返回*/
        return Result.ok(userDTO);
    }

    @ApiOperation(value = "获取当前登录的用户并返回")
    @GetMapping("/me")
    public Result me(){
        /*从ThreadLocal里面获取用户信息*/
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }

}
